<template>
  <div>
    <el-form label-position="top" :disabled="readonly">
      <table style="width: 100%" class="tab-table">
        <tr v-for="(row, index) in matchRules" v-bind:key="index">
          <td width="40%">
            <ko-data-item v-model="row.key" itemType="input" />
          </td>
          <td width="16%">
            <ko-data-item
              v-model="row.operator"
              itemType="select"
              :selections="uiState.operatorList"
            />
          </td>
          <td width="40%">
            <ko-data-item
              v-if="
                row.operator === 'Exists' || row.operator === 'DoesNotExist'
              "
              disabled
              itemType="input"
              value="N/A"
            />
            <ko-data-item
              v-else
              :getter="() => (row.values?.length > 0 ? row.values[0] : '')"
              :setter="value => (row.values = [value])"
              itemType="input"
            />
          </td>
          <td>
            <el-button
              type="text"
              style="font-size: 10px"
              @click="onHandleMatchRuleDelete(index)"
            >
              {{ $t("commons.button.delete") }}
            </el-button>
          </td>
        </tr>
        <tr>
          <td align="left">
            <el-button @click="onHandleMatchRuleAdd()">
              {{ $t("commons.button.add") }}
            </el-button>
          </td>
        </tr>
      </table>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import { reactive } from "vue";
import {
  LabelSelector,
  LabelSelectorRequirement,
  NodeSelectorRequirement
} from "../../../api/k8s";

type Prop = {
  readonly?: boolean;
};
const props = defineProps<Prop>();
const matchRules =
  defineModel<(LabelSelectorRequirement | NodeSelectorRequirement | any)[]>(
    "matchRules"
  );

const uiState = reactive({
  priority: "Preferred",
  operatorList: [
    { label: "Lt", value: "Lt" },
    { label: "Gt", value: "Gt" },
    { label: "Exists", value: "Exists" },
    { label: "DoesNotExist", value: "DoesNotExist" },
    { label: "In", value: "In" },
    { label: "NotIn", value: "NotIn" }
  ]
});

const onHandleMatchRuleAdd = () => {
  matchRules.value.push({
    key: "",
    operator: "In",
    values: []
  });
};

const onHandleMatchRuleDelete = (index: number) => {
  matchRules.value.splice(index, 1);
};
</script>
